package com.kchouse.myadapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.kchouse.MainActivity;
import com.kchouse.R;
import com.kchouse.bean.GivingItem;
import com.kchouse.bean.OrderEvaItem;
import com.kchouse.bean.OrderItem;
import com.kchouse.common.API;
import com.kchouse.common.MyHttpCycleContext;
import com.kchouse.common.MyUtils;
import com.kchouse.common.SharedPreferencesUtil;
import com.kchouse.common.ToastUtils;
import com.kchouse.mine.LoginPhoneActivity;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;

public class OrderEvaAdapter extends RecyclerView.Adapter<OrderEvaAdapter.ViewHolder> {

    private ArrayList<OrderEvaItem> datas;
    private Context context;


    public OrderEvaAdapter(Context context, ArrayList<OrderEvaItem> datas) {
        this.datas = datas;
        this.context = context;
    }

    //创建新View，被LayoutManager所调用
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {

        View view = null;
        ViewHolder vh = null;
        view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.lv_ordereva_item, viewGroup, false);
        vh = new ViewHolder(view);
        return vh;
    }

    //将数据与界面进行绑定的操作
    @SuppressLint("ResourceAsColor")
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int position) {


        final OrderEvaItem item = datas.get(position);
        viewHolder.tv_merchantName.setText(item.getMerchantShortName());
        viewHolder.tv_createTime.setText(item.getConsumeTime());
        viewHolder.tv_projectName.setText(item.getProjectName());

        if (TextUtils.isEmpty(item.getCarNumber())) {
            viewHolder.tv_carNumber.setVisibility(View.GONE);
        } else {
            viewHolder.tv_carNumber.setText(item.getCarNumber());
            viewHolder.tv_carNumber.setVisibility(View.VISIBLE);
        }

        if (item.getStatus().equals("PUSH")) {
            viewHolder.tv_subeva.setText("未确认");
            viewHolder.tv_subeva.setOnClickListener(new EvaOnClick(position, viewHolder.tv_subeva));
            viewHolder.tv_subeva.setClickable(true);
            viewHolder.tv_subeva.setBackground(context.getResources().getDrawable(R.drawable.bg_corners_blue3_btn));
            viewHolder.tv_subeva.setTextColor(context.getResources().getColor(R.color.text_main));
        } else {
            viewHolder.tv_subeva.setText("已确认");
            viewHolder.tv_subeva.setTextColor(context.getResources().getColor(R.color.colorblack));
            viewHolder.tv_subeva.setClickable(false);
            viewHolder.tv_subeva.setBackground(context.getResources().getDrawable(R.drawable.bg_corners_gray_btn2));
            viewHolder.tv_subeva.setOnClickListener(null);
        }


    }


    class EvaOnClick implements View.OnClickListener {

        private int pos;
        private TextView tv_item;

        public EvaOnClick(int pos, TextView tv_item) {
            this.pos = pos;
            this.tv_item = tv_item;
        }

        @Override
        public void onClick(View v) {

            final OrderEvaItem datasitem = datas.get(pos);
//            showdialog_eva(v,datasitem);
            PostConfirmProject(pos, v, tv_item);

        }
    }

    /**
     * 确认项目
     *
     * @param pos
     * @param v
     * @param tv_item
     */
    private void PostConfirmProject(final int pos, final View v, final TextView tv_item) {
        final OrderEvaItem datasitem = datas.get(pos);
        String url = API.PostConfirmProject + datasitem.getId();
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数

        JSONObject ob = new JSONObject();
        ob.put("orderId", datasitem.getOrderId());
        ob.put("projectId", datasitem.getProjectId());
//        params.addFormDataPart("file", file);//上传单个文件
//        params.addFormDataPart("files", files);//上传多个文件
        params.addHeader("token", MainActivity.token);//添加header信息
        params.applicationJson(ob);

        HttpRequest.post(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
//                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    showdialog_eva(v, datasitem);

                    tv_item.setText("已确认");
                    tv_item.setTextColor(context.getResources().getColor(R.color.colorblack));
                    tv_item.setClickable(false);
                    tv_item.setBackground(context.getResources().getDrawable(R.drawable.bg_corners_gray_btn2));
                    tv_item.setOnClickListener(null);
                } else {

                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(context).showToast(data.getString("msg"));
//                    if(data.getString("code").equals("401"))
//                    {
//                        intent.setClass(mContent, LoginPhoneActivity.class);
//                        startActivity(intent);
//                        finish();
//                    }
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
//                dismissdialog();
            }
        });

    }

    private String[] item = {"好", "良", "中", "差", "暂不评价"};
    int index;

    public void showdialog_eva(View v, final OrderEvaItem datasitem) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("请选择");
        builder.setCancelable(false);
        builder.setSingleChoiceItems(item, index, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                index = which;
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
//                Toast.makeText(context, "选择了" + item[index], Toast.LENGTH_SHORT).show();

                switch (item[index]) {
                    case "好":
                        PostProjectEva(datasitem, "GOOD");
                        break;
                    case "良":
                        PostProjectEva(datasitem, "WELL");
                        break;
                    case "中":
                        PostProjectEva(datasitem, "MIDDLE");
                        break;
                    case "差":
                        PostProjectEva(datasitem, "BAD");
                        break;
                    case "暂不评价":
//                        PostProjectEva(datasitem,"");
                        Intent mIntent = new Intent("EvaAction");
                        //发送广播
                        context.sendBroadcast(mIntent);
                        break;
                }

            }
        });
//        builder.setNegativeButton("取消", null);
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

    /**
     * 项目评价
     */
    private void PostProjectEva(OrderEvaItem datasitem, String evaluateStatus) {
        String url = API.PostProjectEva + datasitem.getId() + "?evaluateStatus=" + evaluateStatus;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数

        JSONObject ob = new JSONObject();
        ob.put("orderId", datasitem.getOrderId());
        ob.put("projectId", datasitem.getProjectId());
        params.addHeader("token", MainActivity.token);//添加header信息
        params.applicationJson(ob);

        HttpRequest.post(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
//                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {

                    ToastUtils.getInstanc(context).showToast("谢谢评价");

                    Intent mIntent = new Intent("EvaAction");
                    //发送广播
                    context.sendBroadcast(mIntent);
                } else {

                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(context).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
//                dismissdialog();
            }
        });

    }


    //获取数据的数量
    @Override
    public int getItemCount() {
        return datas.size();
    }

    //自定义的ViewHolder，持有每个Item的的所有界面元素
    public class ViewHolder extends RecyclerView.ViewHolder {

        public TextView tv_merchantName;
        public TextView tv_createTime;
        public TextView tv_projectName;
        public TextView tv_subeva;
        public TextView tv_carNumber;

        public ViewHolder(View view) {
            super(view);
            tv_subeva = (TextView) view.findViewById(R.id.tv_subeva);
            tv_merchantName = (TextView) view.findViewById(R.id.tv_merchantName);
            tv_createTime = (TextView) view.findViewById(R.id.tv_createTime);
            tv_projectName = (TextView) view.findViewById(R.id.tv_projectName);
            tv_carNumber = (TextView) view.findViewById(R.id.tv_carNumber);
        }
    }


}
